import CryptoJS from "crypto-js";

// 生成哈希值
export function TaMd5(text: string): string {
	return CryptoJS.MD5(text).toString()
}

// 生成编号
export function TaGuid(): string {
	return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c: string) => {
		let r = (Math.random() * 16) | 0, v = c == 'x' ? r : (r & 0x3) | 0x8
		return v.toString(16)
	})
}

// Base64 编码
export const TaBase64 = {

	// 普通编码
	encrypt(text: string): string {
		return CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse(text))
	},

	// 普通解码
	decrypt(text: string): string {
		return CryptoJS.enc.Utf8.stringify(CryptoJS.enc.Base64.parse(text));
	},

	Safe: {

		// 安全编码
		encrypt(text: string): string {
			return TaBase64.encrypt(text).replace(/[+/]/g, (m: any) => m === '+' ? '-' : '_')
		},

		// 安全解码
		decrypt(text: string): string {
			return TaBase64.decrypt(text.replace(/[-_]/g, (m: any) => m === '-' ? '+' : '/'))
		}
	}
}

// AES 加密
export const TaEncryptAES = {

	// 数据加密
	encrypt(text: string, skey: string = 'THINKADMIN'): string {
		let iv: CryptoJS.lib.WordArray = CryptoJS.enc.Utf8.parse(TaMd5(skey))
		return CryptoJS.AES.encrypt(text, iv, { iv, padding: CryptoJS.pad.Pkcs7 }).toString()
	},

	// 数据解密
	decrypt(text: string, skey: string = 'THINKADMIN'): string {
		let iv: CryptoJS.lib.WordArray = CryptoJS.enc.Utf8.parse(TaMd5(skey))
		return CryptoJS.AES.decrypt(text, iv, { iv, padding: CryptoJS.pad.Pkcs7 }).toString(CryptoJS.enc.Utf8)
	},
}

// let enc: string = '';
// let txt: string = Math.random().toString();

// console.log('base64', enc = TaBase64.encrypt(txt))
// console.log('base64', enc = TaBase64.decrypt(enc), txt == enc)

// console.log('safe64', enc = TaBase64.Safe.encrypt(txt))
// console.log('safe64', enc = TaBase64.Safe.decrypt(enc), txt == enc)

// console.log('encrypt', enc = TaEncryptAES.encrypt(txt))
// console.log('decrypt', enc = TaEncryptAES.decrypt(enc), txt == enc)